package com.asiainfo.hybridapp.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.asiainfo.hybridapp.R;
import com.asiainfo.hybridapp.configs.ConstantsME;
import com.asiainfo.hybridapp.configs.DebugConfig;
import com.asiainfo.hybridapp.configs.EventBusTag;
import com.asiainfo.hybridapp.service.MyNotificationListenService;
import com.asiainfo.hybridapp.test.WifiScanUtil;
import com.asiainfo.hybridapp.utils.LocationUtil;
import com.framework.customviews.OverScrollView;
import com.framework.utils.PreferencesHelper;
import com.framework.utils.RequestPermissionsUtil;
import com.framework.utils.ScreenUtils;
import com.framework.utils.ToastUtil;
import com.framework.utils.Y;
import com.framework2.dialog.PermissionDialog;
import com.framework2.utils.PicToastUtil;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import custom.org.greenrobot.eventbus.Subscribe;
import custom.org.greenrobot.eventbus.ThreadMode;

/**
 * location
 *
 * @author Yangjie
 * className LocationActivity
 * created at  2017/3/13  16:24
 */
public class LocationActivity extends BaseActivity implements ActivityCompat.OnRequestPermissionsResultCallback {

    @BindView(R.id.tvLocationInfo)
    TextView tvLocationInfo;
    @BindView(R.id.overScrollView)
    OverScrollView overScrollView;
    @BindView(R.id.tvJump)
    TextView tvJump;
    @BindView(R.id.tvJumpHome)
    TextView tvJumpHome;
    @BindView(R.id.tvJumpJSandroid)
    TextView tvJumpJSandroid;
    @BindView(R.id.tvJumpChooseFile)
    TextView tvJumpChooseFile;
    @BindView(R.id.tvJumpCallPhone)
    TextView tvJumpCallPhone;
    @BindView(R.id.tvJumpPolice)
    TextView tvJumpPolice;
    @BindView(R.id.tvOther)
    TextView tvOther;

    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        if ((DebugConfig.TBSx5 && !TextUtils.isEmpty(TBSCookieManagerUtil.getInstance()
//        .decodeCookie(this,
// PreferencesHelper.getInstance().getStringData(ConstantsME.cookies))))
//                || (!DebugConfig.TBSx5 && !TextUtils.isEmpty(CookieManagerUtil.getInstance()
//                .decodeCookie(this,
// PreferencesHelper.getInstance().getStringData(ConstantsME.cookies))))) {
//            RealInterfaceConfig.setBaseServerUrl(EncStringUtil.getInstance().getString
//            (LocationActivity.this,
// ConstantsME.url));
//            startActivity(HomepageActivity.class);
//            finish();
//        }
        setContentView(R.layout.activity_location_test);
        checkUpdate();
        ButterKnife.bind(this);
        ScreenUtils.getInstance().setTranslucentStatus(this, true);
        ScreenUtils.getInstance().setStatusBarTintColor(this,
                getResources().getColor(R.color.main));
        initData();
        initEvent();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager
                .PERMISSION_GRANTED) {
            final PermissionDialog permissionDialog = new PermissionDialog(this);
            permissionDialog.setOnSureClickListener(new PermissionDialog.OnSureClickListener() {
                @Override
                public void onSureClickListener(String info) {
                    permissionDialog.dismiss();
                    RequestPermissionsUtil.getInstance().checkPermissionsThenRequest(LocationActivity.this, new
                            String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                            RequestPermissionsUtil
                            .PERMISSION_LOCATION);
                }
            }).showDialog();
        } else {
            //初始化定位
            initLocation();
            startLocation();
        }
//        tvJumpJSandroid.setVisibility(View.GONE);
//        tvJump.setVisibility(View.GONE);
//        tvJumpPolice.setVisibility(View.GONE);
//        tvJumpChooseFile.setVisibility(View.GONE);
//        tvJumpCallPhone.setVisibility(View.GONE);
//        tvJumpHome.setVisibility(View.GONE);

        startNotificationListenService();
    }

    private void initData() {

    }

    private void initEvent() {

    }

    //eventBus通知 getShopIdSuccess
    @Subscribe(threadMode = ThreadMode.MAIN, tag = EventBusTag.getShopIdSuccess)
    public void getShopIdSuccess(String info) {

    }

    /**
     * 初始化定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void initLocation() {
        //初始化client
        locationClient = new AMapLocationClient(this.getApplicationContext());
        locationOption = getDefaultOption();
        //设置定位参数
        locationClient.setLocationOption(locationOption);
        // 设置定位监听
        locationClient.setLocationListener(locationListener);
    }

    /**
     * 开始定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void startLocation() {
        //根据控件的选择，重新设置定位参数
//        resetOption();
        // 设置定位参数
        locationClient.setLocationOption(locationOption);
        // 启动定位
        locationClient.startLocation();
    }

    /**
     * 停止定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void stopLocation() {
        // 停止定位
        locationClient.stopLocation();
    }

    private void destroyLocation() {
        if (null != locationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
    }

    /**
     * 默认的定位参数
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private AMapLocationClientOption getDefaultOption() {
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setHttpTimeOut(30000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        mOption.setInterval(5000);//可选，设置定位间隔。默认为2秒
        mOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
        mOption.setOnceLocation(false);//可选，设置是否单次定位。默认是false
        mOption.setOnceLocationLatest(false);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,
        // 会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选，
        // 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        mOption.setSensorEnable(false);//可选，设置是否使用传感器。默认是false
        mOption.setWifiScan(true); //可选，设置是否开启wifi扫描。默认为true，如果设置为false
        // 会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mOption.setLocationCacheEnable(true); //可选，设置是否使用缓存定位，默认为true
        return mOption;
    }

    AMapLocation aMapLocation;
    /**
     * 定位监听
     */
    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation location) {
            if (null != location) {
                if (location.getErrorCode() == 0) {
                    aMapLocation = location;
                }
//                Y.y("onLocationChanged:" + location);
                StringBuffer sb = new StringBuffer();
                StringBuffer sbHtml = new StringBuffer();
                //errCode等于0代表定位成功，其他的为定位失败，具体的可以参照官网定位错误码说明
                if (location.getErrorCode() == 0) {
//                    ToastUtil.getInstance().showToast("定位成功!");
                    sb.append("定位成功" + "\n");
                    sb.append("定位类型: " + location.getLocationType() + "\n");
                    sb.append("经    度    : " + location.getLongitude() + "\n");
                    sb.append("纬    度    : " + location.getLatitude() + "\n");
                    sb.append("精    度    : " + location.getAccuracy() + "米" + "\n");
                    sb.append("提供者    : " + location.getProvider() + "\n");

                    sb.append("速    度    : " + location.getSpeed() + "米/秒" + "\n");
                    sb.append("角    度    : " + location.getBearing() + "\n");
                    // 获取当前提供定位服务的卫星个数
                    sb.append("星    数    : " + location.getSatellites() + "\n");
                    sb.append("国    家    : " + location.getCountry() + "\n");
                    sb.append("省            : " + location.getProvince() + "\n");
                    sb.append("市            : " + location.getCity() + "\n");
                    sb.append("城市编码 : " + location.getCityCode() + "\n");
                    sb.append("区            : " + location.getDistrict() + "\n");
                    sb.append("区域 码   : " + location.getAdCode() + "\n");
                    sb.append("地    址    : " + location.getAddress() + "\n");
                    sb.append("兴趣点    : " + location.getPoiName() + "\n");
                    //定位完成的时间
                    sb.append("定位时间: " + LocationUtil.formatUTC(location.getTime(), "yyyy-MM-dd " +
                            "HH:mm:ss") + "\n");
                } else {
                    //定位失败
                    sb.append("定位失败" + "\n");
                    sb.append("错误码:" + location.getErrorCode() + "\n");
                    sb.append("错误信息:" + location.getErrorInfo() + "\n");
                    sb.append("错误描述:" + location.getLocationDetail() + "\n");
                }
                //定位之后的回调时间
                sb.append("回调时间: " + LocationUtil.formatUTC(System.currentTimeMillis(), "yyyy-MM" +
                        "-dd HH:mm:ss") + "\n");

                //解析定位结果，
                String result = sb.toString();
                tvLocationInfo.setText(result);
//                ToastUtil.getInstance().showToast("定位结果：" + result);

                //html测试
                if (location.getErrorCode() == 0) {
                    sbHtml.append("定位成功" + "\n");
                    sbHtml.append("定位类型: " + location.getLocationType() + "<br>");
                    sbHtml.append("经    度    : " + location.getLongitude() + "<br>");
                    sbHtml.append("纬    度    : " + location.getLatitude() + "<br>");
                    sbHtml.append("精    度    : " + location.getAccuracy() + "米" + "<br>");
                    sbHtml.append("提供者    : " + location.getProvider() + "<br>");

                    sbHtml.append("速    度    : " + location.getSpeed() + "米/秒" + "<br>");
                    sbHtml.append("角    度    : " + location.getBearing() + "<br>");
                    // 获取当前提供定位服务的卫星个数
                    sbHtml.append("星    数    : " + location.getSatellites() + "<br>");
                    sbHtml.append("国    家    : " + location.getCountry() + "<br>");
                    sbHtml.append("省            : " + location.getProvince() + "<br>");
                    sbHtml.append("市            : " + location.getCity() + "<br>");
                    sbHtml.append("城市编码 : " + location.getCityCode() + "<br>");
                    sbHtml.append("区            : " + location.getDistrict() + "<br>");
                    sbHtml.append("区域 码   : " + location.getAdCode() + "<br>");
                    sbHtml.append("地    址    : " + location.getAddress() + "<br>");
                    sbHtml.append("兴趣点    : " + location.getPoiName() + "<br>");
                    //定位完成的时间
                    sbHtml.append("定位时间: " + LocationUtil.formatUTC(location.getTime(), "yyyy-MM" +
                            "-dd HH:mm:ss") +
                            "<br>");
                } else {
                    //定位失败
                    sbHtml.append("定位失败" + "<br>");
                    sbHtml.append("错误码:" + location.getErrorCode() + "<br>");
                    sbHtml.append("错误信息:" + location.getErrorInfo() + "<br>");
                    sbHtml.append("错误描述:" + location.getLocationDetail() + "<br>");
                }
                //定位之后的回调时间
                sbHtml.append("回调时间: " + LocationUtil.formatUTC(System.currentTimeMillis(), "yyyy" +
                        "-MM-dd HH:mm:ss") +
                        "<br>");

                PreferencesHelper.getInstance().putInfo(ConstantsME.LATITUDE,
                        String.valueOf(location.getLatitude()));
                PreferencesHelper.getInstance().putInfo(ConstantsME.LATITUDE, sbHtml.toString());
                PreferencesHelper.getInstance().putInfo(ConstantsME.LONGITUDE,
                        String.valueOf(location.getLongitude()));
            } else {
                tvLocationInfo.setText("定位失败，loc is null");
                ToastUtil.getInstance().showToast("定位失败，loc is null");
            }
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[]
            grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Y.y("Homepage--onRequestPermissionsResult:" + requestCode);
        if (requestCode == RequestPermissionsUtil.PERMISSION_LOCATION) {
            if ((grantResults.length >= 1) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                PicToastUtil.showPicToast(LocationActivity.this, "开始定位...");
                //初始化定位
                initLocation();
                startLocation();
            } else {
                ToastUtil.getInstance().showToast("定位权限未开启，请手动开启");
                RequestPermissionsUtil.getInstance().showInstalledAppDetailSettingIntent(this,
                        getPackageName());
            }
        }
    }

    @OnClick({R.id.tvJumpSetting, R.id.tvJumpSettingSpecial, R.id.tvJump, R.id.tvJumpHome,
            R.id.tvJumpJSandroid,R.id.tvOther,
            R.id.tvJumpPolice, R.id.tvJumpChooseFile})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvOther:
                Intent intent=new Intent();
                //包名 包名+类名（全路径）
//                intent.setClassName("io.dcloud.HBuilder", "io.dcloud.PandoraEntryActivity");
                intent.setClassName("io.dcloud.HBuilder", "io.dcloud.PandoraEntry");
//                intent.setClassName("com.asiainfo.universalwebview", "com.cmcc.fdop.activity.MainActivity");
                intent.putExtra("test1","测试一");
                intent.putExtra("test2","测试二");
                startActivity(intent);
                break;
            case R.id.tvJumpSetting:
//                RequestPermissionsUtil.getInstance().showCurrentAppDetailSettingIntent(this);
                String ip = "192.168.10.1";
                WifiScanUtil.getInstance().scan(ip, new WifiScanUtil.IScanResult() {
                    @Override
                    public void onScanSuccess() {
                        Log.e("yy", "onScanSuccess");
                    }

                    @Override
                    public void onScanError(Exception e) {
                        Log.e("yy", "onScanError" + e.getMessage());
                    }
                });
                break;
            case R.id.tvJumpSettingSpecial:
//                RequestPermissionsUtil.getInstance().openNotificationListenSettings(this);
                String ip2 = "192.168.10.1";
                String path = "/picture/";
                WifiScanUtil.getInstance().getDocInfo(ip2, path, "video",
                        new WifiScanUtil.IScanResult() {
                    @Override
                    public void onScanSuccess() {
                        Log.e("yy", "onScanSuccess");
                    }

                    @Override
                    public void onScanError(Exception e) {
                        Log.e("yy", "onScanError" + e.getMessage());
                    }
                });
                break;

            case R.id.tvJumpJSandroid:
                Bundle b1 = new Bundle();
//                b.putString(ConstantsME.title, "百度测试");
//                b.putString(ConstantsME.url, "http:www.baidu.com");
                b1.putString(ConstantsME.title, "本地js-android调用");
                b1.putString(ConstantsME.url, "file:///android_asset/html5/html/html5test.html");
                if (DebugConfig.TBSx5) {
                    startActivity(CommonFullTBSWebViewActivity.class, b1);
                } else {
//                    startActivity(CommonFullWebViewActivity.class, b);
                    startActivity(TestCommonFullWebViewToolBarActivity.class, b1);
                }
//                finish();
                break;
            case R.id.tvJump:
                if (aMapLocation == null) {
                    ToastUtil.getInstance().showToast("未获取定位");
                    return;
                }
                Bundle b = new Bundle();
//                b.putString(ConstantsME.title, "百度测试");
//                b.putString(ConstantsME.url, "http:www.baidu.com");

                b.putString(ConstantsME.title, "定位测试");
                b.putString(ConstantsME.url,
                        "http://123.59.26.108/businessHshERP/login/o2o?custId" +
                                "=51793948696735366f465738436e62443433632f66513d3d&custNumber" +
                                "=61724e49464c6d41636779506b4e41503139685757673d3d");
                b.putString(ConstantsME.url,
                        "https://app.10086.cn/leadeon-cmcc-static/v2.0/pages/transit/transit" +
                                ".html?province=210&city=210&prodId=1073605&sku_id=1053350&ptype" +
                                "=50000");
//                b.putString(ConstantsME.url, "http://192.168.0.151:8080");
//                b.putString(ConstantsME.url, "http://www.baidu.com");
                if (DebugConfig.TBSx5) {
                    startActivity(CommonFullTBSWebViewActivity.class, b);
                } else {
//                    startActivity(CommonFullWebViewActivity.class, b);
//                    startActivity(TestCommonFullWebViewToolBarActivity.class, b);
                    startActivity(new Intent(this, TestCommonFullWebViewToolBarActivity.class).putExtra
                            ("aMapLocation", aMapLocation).putExtras(b));
                }
//                finish();
                break;
            case R.id.tvJumpPolice:
                Bundle b2 = new Bundle();
//                b2.putString(ConstantsME.title, "北京公安测试");
//                b2.putString(ConstantsME.url, "http://221.179.129.248:8081/klyj/");
                b2.putString(ConstantsME.title, "违章查询");
                b2.putString(ConstantsME.url, "https://bl" +
                        ".cx580.com/illegal?user_id=00002063&user_from=ZGYD2018&token=TLAuVBlE" +
                        "%2FQZhDSs86y9aYQUBh6DN5amHLLqwkatz5VM%3D");

                b2.putString(ConstantsME.title, "本地H5视频");
                b2.putString(ConstantsME.url, "file:///android_asset/html5/html/video.html");
                b2.putString(ConstantsME.url, "http://andway.che.ge.chinamobile.com/h5/help" +
                        ".html?type=X2&devicePreparationType=0&os=ios");
                if (DebugConfig.TBSx5) {
                    startActivity(CommonFullTBSWebViewActivity.class, b2);
                } else {
                    startActivity(new Intent(this, TestCommonFullWebViewToolBarActivity.class).putExtras(b2));
                }
                break;
            case R.id.tvJumpChooseFile:
                Bundle bund = new Bundle();
                bund.putString(ConstantsME.title, "本地js-android调用-chooseFille");
                bund.putString(ConstantsME.url, "file:///android_asset/html5/html/html5ChooseFile" +
                        ".html");
                if (DebugConfig.TBSx5) {
                    startActivity(CommonFullTBSWebViewActivity.class, bund);
                } else {
                    startActivity(new Intent(this, TestCommonFullWebViewToolBar11Activity.class).putExtras(bund));
                }
                break;
            case R.id.tvJumpCallPhone:
                Bundle bundCallphone = new Bundle();
                bundCallphone.putString(ConstantsME.title, "本地js-android调用-callPhone");
                bundCallphone.putString(ConstantsME.url, "file:///android_asset/html5/html" +
                        "/html5callphone.html");
                if (DebugConfig.TBSx5) {
                    startActivity(CommonFullTBSWebViewActivity.class, bundCallphone);
                } else {
                    startActivity(new Intent(this, TestCommonFullWebViewToolBar11Activity.class).putExtras(bundCallphone));
                }
                break;
            case R.id.tvJumpHome:
                startActivity(HomepageActivity.class);
                break;
            default:break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroyLocation();
    }

    // 启动监听消息通知服务
    private void startNotificationListenService() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            Intent intent = new Intent(LocationActivity.this,
                    MyNotificationListenService.class);
            startService(intent);
        } else {
            Toast.makeText(LocationActivity.this, "手机的系统不支持此功能", Toast.LENGTH_SHORT).show();
        }
    }

    private void checkUpdate() {

//        PgyUpdateManager.register(LocationActivity.this,
//                new UpdateManagerListener() {
//
//                    @Override
//                    public void onUpdateAvailable(final String result) {
//
//                        // 将新版本信息封装到AppBean中
//                        final AppBean appBean = getAppBeanFromString(result);
//                        new AlertDialog.Builder(LocationActivity.this)
//                                .setTitle("发现新版本" + (TextUtils.isEmpty(appBean.getVersionName()
//                                ) ? "" :
//                                        appBean.getVersionName()))
//                                .setMessage(TextUtils.isEmpty(appBean.getReleaseNote()) ? "" :
//                                appBean.getReleaseNote())
//                                .setNegativeButton(
//                                        "取消",
//                                        new DialogInterface.OnClickListener() {
//                                            @Override
//                                            public void onClick(DialogInterface dialog, int
//                                            which) {
//                                                dialog.dismiss();
//                                            }
//                                        })
//                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                                    @Override
//                                    public void onClick(DialogInterface dialog, int which) {
//                                        startDownloadTask(LocationActivity.this, appBean
//                                        .getDownloadURL());
//                                    }
//                                }).show();
//                    }
//
//                    @Override
//                    public void onNoUpdateAvailable() {
//                    }
//                });
    }
}
